All files / app/api/org/users/[id]/role route.ts

86.66% Statements 39/45
96.15% Branches 25/26
33.33% Functions 1/3
86.66% Lines 39/45

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118        1x 1x 1x 1x 1x   1x       10x 10x 10x 10x   10x 1x           9x     9x                 9x 1x     8x 8x 8x 8x 8x     8x 1x             7x 1x             6x 1x             5x 5x 1x       4x 1x             3x 2x 1x         1x 1x               1x   1x                        
/**
 * PATCH /api/org/users/[id]/role
 * Change a user's role within the organisation
 */
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { getCurrentUser, fetchAuthSession } from "aws-amplify/auth/server";
import { runWithAmplifyServerContext } from "@/lib/amplify-server-utils";
import { getUser, updateUserRole } from "@/lib/cognito-admin";
 
export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id: targetUserId } = await params;
    const body = await request.json();
    const { role: newRole } = body as { role: "owner" | "admin" | "member" };
 
    if (!newRole || !["owner", "admin", "member"].includes(newRole)) {
      return NextResponse.json(
        { error: "Invalid role. Must be owner, admin, or member" },
        { status: 400 }
      );
    }
 
    const cookieStore = await cookies();
 
    // Get current user's session
    const session = await runWithAmplifyServerContext({
      nextServerContext: { cookies: async () => cookieStore },
      operation: async (context) => {
        const user = await getCurrentUser(context);
        const session = await fetchAuthSession(context);
        return { user, session };
      },
    });
 
    if (!session.session.tokens?.idToken) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }
 
    const idToken = session.session.tokens.idToken;
    const currentUserType = idToken.payload["custom:user_type"] as string | undefined;
    const currentTenantId = idToken.payload["custom:tenant_id"] as string | undefined;
    const currentRole = idToken.payload["custom:role"] as string | undefined;
    const currentUserId = session.user.userId;
 
    // Only org users can access this
    if (currentUserType !== "org" || !currentTenantId) {
      return NextResponse.json(
        { error: "Only organisation users can access this" },
        { status: 403 }
      );
    }
 
    // Only owner or admin can change roles
    if (currentRole !== "owner" && currentRole !== "admin") {
      return NextResponse.json(
        { error: "Only owner or admin can change roles" },
        { status: 403 }
      );
    }
 
    // Cannot change your own role
    if (targetUserId === currentUserId) {
      return NextResponse.json(
        { error: "Cannot change your own role" },
        { status: 400 }
      );
    }
 
    // Get target user
    const targetUser = await getUser(targetUserId);
    if (!targetUser) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }
 
    // Verify target user is in the same tenant
    if (targetUser.tenantId !== currentTenantId) {
      return NextResponse.json(
        { error: "User is not in your organisation" },
        { status: 403 }
      );
    }
 
    // Admins cannot change owner roles or promote to owner
    if (currentRole === "admin") {
      if (targetUser.role === "owner") {
        return NextResponse.json(
          { error: "Admins cannot change owner roles" },
          { status: 403 }
        );
      }
      Eif (newRole === "owner") {
        return NextResponse.json(
          { error: "Admins cannot promote to owner" },
          { status: 403 }
        );
      }
    }
 
    // Update user's role
    await updateUserRole(targetUserId, newRole);
 
    return NextResponse.json({
      success: true,
      user: { ...targetUser, role: newRole },
    });
  } catch (error) {
    console.error("Error changing role:", error);
    return NextResponse.json(
      { error: "Failed to change role" },
      { status: 500 }
    );
  }
}